package jdbcDemo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    User user = null;

    public UserDao(Connection conn, PreparedStatement ps) {
        this.conn = conn;
        this.ps = ps;
    }

    public UserDao() {
        DBUtil.connetcDB();
        conn = DBUtil.getConn();
    }


    public void addStudent(User user) {

        try {
            this.user = user;
            String sql = "INSERT INTO  userInfo VALUES ( ? ,  ? )";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.userName);
            ps.setString(2, user.password);
            ps.execute();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void query(String userName) {
        String sql = "SELECT * FROM userInfo WHERE userName = ? ";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, userName);
            rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println("userName = "+
                        rs.getString("userName")+
                        "password = "+
                        rs.getString("password"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void delete(String userName) {
        String sql = "DELETE FROM userInfo WHERE userName = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, userName);
            ps.execute();
            System.out.println("已经删除名字为"+ userName +" 的用户的数据");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    public void update() {
        String sql = "UPDATE userInfo SET password = 'passwordUpdated' WHERE name = '大白'";
        try {
            ps = conn.prepareStatement(sql);
            ps.execute();
            System.out.println("已经修改了李白的的数据");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void queryAll() {
        String sql = "SELECT * FROM userInfo";
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            System.out.println("当前表内全部结果,如下:");
            while(rs.next()){
                String userName= rs.getString("userName");
                String password = rs.getString("password");
                System.out.println(userName + ", " +password);
            }
            System.out.println("");

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
}


